package smartbooksdb.service;

import java.util.Date;
import java.util.List;

import smartbooksdb.exception.MandatoryFieldException;
import smartbooksdb.exception.UserException;
import smartbooksdb.hibernatebean.User;
import smartbooksdb.util.CommonConstantsDB;
import smartbooksdb.util.CommonFunctionsDB;
import smartbooksdb.valuebean.Credentials;

public class UserService implements CommonConstantsDB {

	/**
	 * This method returns the number of active admins present in the entire
	 * system. It does not restrict the search to a particular org.
	 * 
	 * @return numberOfAdmins
	 */
	public long getNumberOfAdmin() {
		// Fetch number of active admins
		UserDAO userDAO = UserDAO.getInstance();
		return userDAO.getNumberOfAdmin();
	}

	/**
	 * This method tells whether the username is available for creation or not.
	 * The isCaseSensitive parameter suggests whether to perform a case
	 * sensitive check or not.
	 * 
	 * @param username
	 * @param isCaseSensitive
	 * @return isUsernameAvailable
	 * @throws MandatoryFieldException
	 *             if username is either null or blank
	 */
	public boolean isUsernameAvailable(String username, boolean isCaseSensitive)
			throws MandatoryFieldException {
		// Mandatory check on username. Implemented this validation because
		// database returns true for null or blank value of username.
		CommonFunctionsDB.validateUsername(username);

		// Check if username is available
		UserDAO userDAO = UserDAO.getInstance();
		return userDAO.isUsernameAvailable(username, isCaseSensitive);
	}

	/**
	 * This method is used to create a user. The entire user detail is present
	 * in the user object.
	 * 
	 * @param user
	 * @throws MandatoryFieldException
	 *             if user object is null
	 * @throws UserException
	 *             if any exception is thrown while creating the user
	 */
	public void createUser(User user) throws MandatoryFieldException,
			UserException {
		// Mandatory check on user
		CommonFunctionsDB.validateUser(user);

		// Set updatedDate and status before creating a record
		user.setUpdatedDate(new Date());
		user.setStatus(ACTIVE);

		// Creates the user
		UserDAO userDAO = UserDAO.getInstance();
		userDAO.createUser(user);
	}

	/**
	 * This method verifies the login credentials of the active user and if
	 * valid, returns the user details.
	 * 
	 * @param credentials
	 * @return User
	 */
	public User getUser(Credentials credentials) {
		// Fetch user details for valid user
		UserDAO userDAO = UserDAO.getInstance();
		return userDAO.getUser(credentials);
	}

	/**
	 * This method returns all the active users in the system irrespective of
	 * their roles.
	 * 
	 * @return List<User>
	 */
	public List<User> getAllUsers() {
		// Fetch all the active users in the system
		UserDAO userDAO = UserDAO.getInstance();
		return userDAO.getAllUsers();
	}
}